#!/bin/bash
DEFAULT_FILE=background.xml
DEFAULT_TRANSITION=5
output_head() {
cat >"$1" <<EOF
<background>
  <starttime>
    <year>2009</year>
    <month>08</month>
    <day>04</day>
    <hour>00</hour>
    <minute>00</minute>
    <second>00</second>
  </starttime>
EOF
}

output_end() {
cat >>"$1" <<EOF
</background>
EOF
}

list_files() {
	lastfile=
	firstfile=$(ls|head -1)
	for f in $path/*; do
		if [ -n "$lastfile" ]; then
			cat >> "$1" <<EOF
  <transition>
    <duration>$transition_d</duration>
    <from>$lastfile</from>
    <to>$f</to>
  </transition>
EOF
		fi

		cat >> "$1" <<EOF
  <static>
    <duration>$static_d</duration>
    <file>$f</file>
  </static>
EOF
		lastfile=$f

	done

	cat >> "$1" <<EOF
  <transition>
    <duration>$transition_d</duration>
    <from>$lastfile</from>
    <to>$firstfile</to>
  </transition>
EOF
}

if [ -z "$2" ]; then
	echo "usage: genxml.sh duration_minutes image_dir"
	exit 255
fi
seconds=$(($1 * 60))
transition_d=$DEFAULT_TRANSITION
static_d=$(($seconds - $transition_d))
path=$(realpath $2)

output_head "$path/$DEFAULT_FILE"
list_files "$path/$DEFAULT_FILE"
output_end "$path/$DEFAULT_FILE"
